<template>
  <div class="chat-container">
    <el-container class="chat-main-container">
      <el-aside class="chat-left-chatlist">
        <el-popover
          :width="280"
          placement="bottom"
          :visible="chatListSearchPopoverVisible"
        >
          <template #reference>
            <el-input
              style="padding: 4px 20px"
              v-model="searchKey"
              clearable
              :suffix-icon="Search"
              placeholder="请输入聊天对话关键词"
            />
          </template>
          <ul v-for="item in filterChatList">
            <li @click="gotoChat(item)">
              {{ item.targetName }}&nbsp;&nbsp;{{
                item.jobInfoVo.companyName
              }}&nbsp;&nbsp;{{ item.targetJob }}
            </li>
          </ul>
        </el-popover>
        <el-scrollbar style="height: 92%">
          <div v-for="item in chatList" @click="gotoChat(item)">
            <el-popover trigger="contextmenu" placement="bottom-end">
              <template #reference>
                <div class="chat-list-item">
                  <el-avatar :src="item.targetAvatar" :size="48" />
                  <div class="chat-list-item-right">
                    <div class="chat-list-item-header">
                      <div
                        style="
                          overflow: hidden;
                          white-space: nowrap;
                          text-overflow: ellipsis;
                          width: 75%;
                        "
                      >
                        <span>{{ item.targetName }}</span>
                        <span style="margin-left: 8px; font-size: 13px">
                          {{ item.jobInfoVo.companyName }}
                        </span>
                        <span style="margin-left: 8px; font-size: 13px">
                          {{ item.targetJob }}
                        </span>
                      </div>
                      <div style="font-size: 14px">
                        {{ handleChatListTime(item.lastTime) }}
                      </div>
                    </div>
                    <p class="chat-list-item-footer">
                      {{ item.recentMessage }}
                    </p>
                  </div>
                </div>
              </template>
              <ul class="contextmenu">
                <li @click="deleteChatListById(item.id)">删除对话</li>
              </ul>
            </el-popover>
          </div>
        </el-scrollbar>
      </el-aside>
      <el-main class="chat-right-chatmessage">
        <div v-if="selectedChatList" style="height: 100%">
          <div style="padding: 20px; color: var(--el-text-color-regular)">
            {{ selectedChatList.targetName }} &nbsp;&nbsp;
            {{ selectedChatList.jobInfoVo.companyName }}&nbsp;&nbsp;
            {{ selectedChatList.targetJob }}
          </div>
          <div style="font-size: 18px; padding-left: 20px; cursor: pointer">
            <span>{{ selectedChatList.jobInfoVo.jname }}</span>
            &nbsp;&nbsp;
            <el-text type="primary" size="large">
              {{ selectedChatList.jobInfoVo.minSalary }}K-
              {{ selectedChatList.jobInfoVo.maxSalary }}K
            </el-text>
            &nbsp;&nbsp;
            <span>{{ selectedChatList.jobInfoVo.jlocation }}</span>
          </div>
          <div class="chat-container-content">
            <el-scrollbar>
              <div class="message-list-content">
                <div class="chat-msg-nothing">
                  <span class="msg-nothing">没有更多消息了~</span>
                </div>
                <div
                  v-for="(item, index) in messageStore.chatMessages"
                  :key="index"
                  ref="child"
                >
                  <div class="msg-time">
                    <span class="time">{{ handleTime(item.createTime) }}</span>
                  </div>
                  <div
                    class="msg-item"
                    :class="
                      userStore.userInfo.username === item.senderUsername
                        ? 'is-me'
                        : ''
                    "
                  >
                    <img :src="item.senderAvatar" class="msg-avatar" />
                    <div class="message">
                      <el-image
                        class="message-image"
                        :src="item.message"
                        :zoom-rate="1.2"
                        :preview-src-list="[item.message]"
                        fit="scale-down"
                        v-if="item.type == 2"
                      />
                      <div class="message-content" v-else>
                        {{ item.message }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>
          <div class="chat-send-box">
            <div class="chat-tools">
              <!-- <el-upload
                :action="File_API.OTHER_URL"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
              >
                <svg-icon
                  name="picture"
                  height="26px"
                  width="26px"
                  :color="picIconColor"
                  @mouseover="picIconColor = '#80B9F2'"
                  @mouseleave="picIconColor = '#111111'"
                  style="cursor: pointer"
                />
              </el-upload> -->
            </div>
            <div class="chat-editor">
              <textarea
                v-model="chatCurrentMsg.message"
                class="chat-textarea"
                maxlength="500"
                @keyup.enter.native="sendChatTextMsg"
              />
            </div>
            <div class="chat-container-bottom">
              <span class="chat-tips">
                {{ chatCurrentMsg.message.length }}/500
              </span>
              <el-button
                style="width: 75px"
                type="primary"
                @click="sendChatTextMsg"
              >
                发送
              </el-button>
            </div>
          </div>
        </div>
        <div v-else class="chat-blank-list">
          <el-image
            style="width: 250px; height: 250px"
            :src="image"
            fit="fill"
          />
          <br />
          <div>您还未选中或者发起聊天，快去跟HR聊一聊吧</div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { reqDeleteChatListById, reqGetChatListBySeeker } from '@/api/chat'
import { ChatListType, AddChatMessageParams } from '@/api/chat/type'
import { ElMessage } from 'element-plus'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { formatDate, handleChatListTime } from '@/utils/time'
import usemessageStore from '@/store/modules/message'
import useUserStore from '@/store/modules/user'
import { handleTime } from '@/utils/time'
import { useRoute } from 'vue-router'
import { JobType } from '@/api/job/type'

onMounted(() => {
  getMyChatList()
})

const currentJobId = computed(() => {
  if (route.query.jId) {
    return parseInt(route.query.jId as string)
  } else {
    return 0
  }
})

const child = ref()
const image = new URL('@/assets/images/blankMessage.png', import.meta.url).href
const route = useRoute()
const selectedChatList = ref<ChatListType>()
const chatList = ref<ChatListType[]>([])
const searchKey = ref('')

const messageStore = usemessageStore()
const userStore = useUserStore()

const chatListSearchPopoverVisible = computed(() => {
  if (chatList.value.length === 0 || searchKey.value == '') {
    return false
  } else {
    return true
  }
})

function checkChatList(item: ChatListType) {
  if (
    item.targetName.includes(searchKey.value) ||
    item.targetJob.includes(searchKey.value) ||
    item.jobInfoVo.jname.includes(searchKey.value) ||
    item.jobInfoVo.companyName.includes(searchKey.value) ||
    item.recentMessage.includes(searchKey.value)
  ) {
    return true
  } else {
    return false
  }
}

const filterChatList = computed(() => {
  if (chatListSearchPopoverVisible.value) {
    return chatList.value.filter(checkChatList)
  } else {
    return []
  }
})

//滚动底部
watch(
  () => messageStore.chatMessages,
  (newVal) => {
    nextTick(() => {
      if (newVal.length >= 1) child.value[newVal.length - 1].scrollIntoView() // 关键代码
    })
  },
  {
    deep: true, //深度监听
  },
)

const chatCurrentMsg = ref<AddChatMessageParams>({
  /*职位Id */
  jobId: 0,
  /*简历Id */
  resumeId: 0,
  /*接收方用户名 */
  recipientUsername: '',
  /*接收方称呼 */
  recipientName: '',
  /*接收方头像 */
  recipientAvatar: '',
  /*聊天信息 */
  message: '',
  type: 1,
})

const getMyChatList = async () => {
  try {
    const { data } = await reqGetChatListBySeeker()
    chatList.value = data.data
    handleChatList(data.data)
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const handleChatList = (data: ChatListType[]) => {
  if (currentJobId.value !== 0) {
    let oneChatList = data.filter((item) => {
      if (item.jobInfoVo.jobId === currentJobId.value) return true
    })
    if (oneChatList.length > 0) {
      gotoChat(oneChatList[oneChatList.length - 1])
    } else {
      let data = sessionStorage.getItem('jobInfo')
      let jobInfo = ref<JobType>()
      if (data != null) {
        jobInfo.value = JSON.parse(data)
      }
      let newChatList: ChatListType = {
        /* */
        id: 0,

        /* */
        jobInfoVo: {
          /*职位ID */
          jobId: jobInfo.value?.id ? jobInfo.value?.id : 0,

          /* */
          companyId: jobInfo.value?.companyInfoVo.id
            ? jobInfo.value?.companyInfoVo.id
            : 0,

          /* */
          companyName: jobInfo.value?.companyInfoVo.name
            ? jobInfo.value?.companyInfoVo.name
            : '',

          /* */
          companyLogo: jobInfo.value?.companyInfoVo.logo
            ? jobInfo.value?.companyInfoVo.logo
            : '',

          /* */
          minSalary: jobInfo.value?.minSalary ? jobInfo.value?.minSalary : 0,

          /* */
          maxSalary: jobInfo.value?.maxSalary ? jobInfo.value?.maxSalary : 0,

          /* */
          jeduction: jobInfo.value?.eduction ? jobInfo.value?.eduction : 0,

          /* */
          jexperience: jobInfo.value?.experience
            ? jobInfo.value?.experience
            : 0,

          /* */
          jlocation: jobInfo.value?.location ? jobInfo.value?.location : '',

          /* */
          jtagName: jobInfo.value?.tagName ? jobInfo.value?.tagName : '',

          /* */
          jname: jobInfo.value?.name ? jobInfo.value?.name : '',

          /* */
          jstatus: jobInfo.value?.status ? jobInfo.value?.status : 0,

          /* */
          jtype: jobInfo.value?.type ? jobInfo.value?.type : 0,
        },

        /* */
        targetAvatar: jobInfo.value?.jorHrInfoVo.avatar
          ? jobInfo.value?.jorHrInfoVo.avatar
          : '',

        /* */
        targetName: jobInfo.value?.jorHrInfoVo.realname
          ? jobInfo.value?.jorHrInfoVo.realname
          : '',

        /* */
        targetUsername: jobInfo.value?.jorHrInfoVo.username
          ? jobInfo.value?.jorHrInfoVo.username
          : '',

        /* */
        targetJob: jobInfo.value?.jorHrInfoVo.job
          ? jobInfo.value?.jorHrInfoVo.job
          : '',

        /* */
        recentMessage: '',

        resumeId: 0,

        /* */
        lastTime: '',
      }
      chatList.value.unshift(newChatList)
      gotoChat(newChatList)
    }
  }
}

const deleteChatListById = async (chatListId: number) => {
  try {
    const { data } = await reqDeleteChatListById(chatListId)
    ElMessage.success(data.message)
    getMyChatList()
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

const gotoChat = (item: ChatListType) => {
  if (item.targetUsername == selectedChatList.value?.targetUsername) {
    return
  }
  selectedChatList.value = item
  messageStore.chatWSConnect(item.targetUsername)
  chatCurrentMsg.value.jobId = item.jobInfoVo.jobId
  chatCurrentMsg.value.resumeId = item.resumeId
  chatCurrentMsg.value.recipientAvatar = item.targetAvatar
  chatCurrentMsg.value.recipientName = item.targetName
  chatCurrentMsg.value.recipientUsername = item.targetUsername
}

const sendChatTextMsg = async () => {
  chatCurrentMsg.value.type = 1
  await messageStore.sendMessage(chatCurrentMsg.value)
  chatCurrentMsg.value.message = ''
}
</script>

<style scoped lang="scss">
.chat-container {
  height: calc(100vh - $base-menu-height);
  width: 100vw;
  background-color: rgb(208, 251, 237);
  display: flex;
  justify-content: center;
  align-items: center;

  .chat-main-container {
    display: flex;
    background-color: white;
    border-radius: 12px;
    height: 94%;
    max-width: 78vw;
    min-width: 800px;

    .chat-left-chatlist {
      width: 320px;
      border-right: 1px solid rgb(226, 226, 226);
      padding: 8px 0px;

      .chat-list-item {
        padding: 10px 20px;
        width: 100%;
        display: flex;
        cursor: pointer;

        .chat-list-item-right {
          width: 80%;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          margin-left: 8px;

          .chat-list-item-header {
            display: flex;
            justify-content: space-between;
          }

          .chat-list-item-footer {
            font-size: 14px;
            color: var(--el-color-info);
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
    }

    .chat-right-chatmessage {
      height: 100%;
      max-width: calc(100% - 320px);
      padding: 0px;

      .chat-container-content {
        height: calc(100% - 74px - 144px);
        -webkit-box-flex: 1;
        -ms-flex: 1;
        flex: 1;
        position: relative;
        overflow-x: hidden;

        .message-list-content {
          overflow: auto;
          display: flex;
          flex-direction: column;

          .chat-msg-nothing {
            padding: 12px 0 12px;
            text-align: center;

            .msg-nothing {
              color: #999;
              font-size: 12px;
              line-height: 22px;
              margin: 0 10px;
            }
          }

          .msg-time {
            padding: 10px 0px;
            text-align: center;

            .time {
              color: #999;
              font-size: 12px;
              line-height: 22px;
              margin: 0 10px;
            }
          }

          .msg-item {
            min-height: 40px;
            padding: 0 16px 16px 20px;
            overflow: hidden;
            position: relative;
            display: flex;

            .msg-avatar {
              width: 34px;
              height: 34px;
              cursor: pointer;
              border-radius: 50%;
            }

            .message {
              max-width: 480px;
              margin: 0 10px;
              position: relative;
              overflow: hidden;

              .message-content {
                line-height: 1.5;
                font-size: 14px;
                min-height: 37px;
                padding: 8px 16px;
                word-wrap: break-word;
                word-break: break-word;
                border-radius: 0 16px 16px 16px;
                overflow: hidden;
                background: #cccccc;
              }

              .message-image {
                border-radius: 0 16px 16px 16px;
                height: 160px;
                overflow: hidden;
              }
            }
          }

          .is-me .message {
            position: relative;
            margin-left: auto;
            color: #fff;

            .message-content {
              background: #80b9f2;
              border-radius: 16px 0 16px 16px;
            }

            .message-image {
              border-radius: 16px 0 16px 16px;
            }
          }

          .is-me .msg-avatar {
            order: 1;
          }
        }
      }

      .chat-send-box {
        height: 144px;
        padding: 0 16px;
        border-top: 1px solid #d8d8d8;
        position: relative;

        .chat-tools {
          height: 36px;
          display: flex;
          align-items: center;
        }

        .chat-editor {
          display: block;
          height: 58px;

          .chat-textarea {
            height: 100%;
            width: 100%;
            font-size: 14px;
            letter-spacing: 1px;
            padding: 0px;
            word-wrap: break-word;
            background-color: #f4f5f7;
            border: none;
            outline: none;
            resize: none;
          }
        }

        .chat-textarea::-webkit-scrollbar {
          width: 6px;
          height: 6px;
        }

        .chat-textarea::-webkit-scrollbar-thumb {
          border-radius: 3px;
          -moz-border-radius: 3px;
          -webkit-border-radius: 3px;
          background-color: #c3c3c3;
        }

        .chat-textarea::-webkit-scrollbar-track {
          background-color: transparent;
        }

        .chat-container-bottom {
          position: relative;
          text-align: right;
          padding-right: 20px;
          margin-top: 6px;

          .chat-tips {
            font-size: 13px;
            padding-right: 10px;
            color: #aeaeae;
          }
        }
      }

      .chat-blank-list {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        width: 100%;
        height: 90%;
        color: #aeaeae;
      }
    }
  }
}

.contextmenu {
  width: 100px;
  margin-top: -48px;
  border: 1px solid #ccc;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 2px 0;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.2);
}

.contextmenu li {
  margin: 0;
  padding: 6px 16px;
}

li:hover {
  color: var(--el-color-primary);
  cursor: pointer;
}
</style>
